package br.ufms.odontologico.bo;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

@ViewScoped
@ManagedBean
public class GenericBO<P> {
	
	private EntityManagerFactory emf;
	private EntityManager em;
	

	public Boolean insert(P obj){
		Boolean result = true;
		try{
			getEm().persist(obj);
		}catch (Exception e) {
			e.printStackTrace();
			result=false;
		}
		return result;
	}

	public P update(P obj){
		getEm().persist(obj);
		return obj;
	}
	
	public P updateOnly(P obj){
		return getEm().merge(obj);
	}

	
	public Boolean delete(P obj){
		Boolean result = true;
		try{
			getEm().remove(obj);
		}catch (Exception e) {
			e.printStackTrace();
			result=false;
		}
		return result;
	}

	public Boolean delete(List<P> obj){
		Boolean result = true;
		try{
			for (P p : obj) {
				getEm().remove(p);
			}
		}catch (Exception e) {
			e.printStackTrace();
			result=false;
		}
		return result;
	}

	public EntityManager getEm() {
		if(em==null){
			if(emf==null) emf = Persistence.createEntityManagerFactory("OdontoSys");
			em = emf.createEntityManager();
		}
		return em;
	}

	public EntityManagerFactory getEmf() {
		return emf;
	}

	public void setEmf(EntityManagerFactory emf) {
		this.emf = emf;
	}


}
